package com.gewu.pm.ui.activity.funds;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.gewu.pm.R;
import com.gewu.pm.aop.SingleClick;
import com.gewu.pm.app.AppActivity;
import com.gewu.pm.bean.FreezerDetailBean;
import com.gewu.pm.http.glide.GlideApp;
import com.gewu.pm.other.IntentKey;
import com.gewu.pm.ui.activity.ImageSelectActivity;
import com.gewu.pm.ui.dialog.SelectSubmitterDialog;
import com.gewu.pm.ui.dialog.SelectionListDialog;
import com.gewu.pm.utils.MoneyInputHelper;
import com.gewu.pm.utils.TextStarUtils;
import com.hjq.bar.TitleBar;
import com.hjq.base.BaseDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 编辑/新增冰柜页面（共用）
 * 
 * 功能：
 * 1. 通过 type 区分新增/编辑模式
 * 2. 表单输入和验证
 * 3. 单张图片上传和删除
 * 4. 单选CheckBox互斥逻辑
 * 5. 数据提交
 */
public final class FreezerEditActivity extends AppActivity
        implements ImageSelectActivity.OnPhotoSelectListener {

    private static final int TYPE_ADD = 0;      // 新增模式
    private static final int TYPE_EDIT = 1;     // 编辑模式

    private static final int PHOTO_TYPE_FREEZER = 0;    // 冰柜照片
    private static final int PHOTO_TYPE_NAMEPLATE = 1;  // 铭牌照片

    private int mEditType = TYPE_ADD;           // 编辑类型（默认新增）
    private int mCurrentPhotoType = -1;         // 当前选择的照片类型

    // 标题栏
    private TitleBar mTitleBar;

    // 冰柜管理
    private TextView mFreezerNameLabel;
    private EditText mFreezerNameEdit;
    private TextView mNameplateCodeLabel;
    private EditText mNameplateCodeEdit;
    private TextView mFreezerTypeLabel;
    private TextView mFreezerTypeValue;
    private TextView mTerminalNameLabel;
    private TextView mTerminalNameValue;
    private TextView mTerminalCodeValue;
    private TextView mHasSubsidyLabel;
    private CheckBox mSubsidyYesCheckBox;
    private CheckBox mSubsidyNoCheckBox;
    private TextView mIsPlacedLabel;
    private CheckBox mPlacedYesCheckBox;
    private CheckBox mPlacedNoCheckBox;
    private TextView mSubsidyAmountLabel;
    private EditText mSubsidyAmountEdit;
    private TextView mFreezerPhotoLabel;
    private ImageView mFreezerPhotoView;
    private ImageView mFreezerPhotoDeleteView;
    private String mFreezerPhotoPath;
    private TextView mNameplatePhotoLabel;
    private ImageView mNameplatePhotoView;
    private ImageView mNameplatePhotoDeleteView;
    private String mNameplatePhotoPath;

    // 配送商信息
    private TextView mDeliveryProviderLabel;
    private TextView mDeliveryProviderValue;
    private TextView mVehicleCodeLabel;
    private TextView mVehicleCodeValue;
    private TextView mSalespersonLabel;
    private TextView mSalespersonValue;
    private TextView mSalesAreaLabel;
    private TextView mSalesAreaValue;

    // 保存按钮
    private TextView mSaveButton;

    private FreezerDetailBean mFreezerData;

    /**
     * 启动新增冰柜页面
     */
    public static void startForAdd(Context context) {
        Intent intent = new Intent(context, FreezerEditActivity.class);
        intent.putExtra(IntentKey.TYPE, TYPE_ADD);
        context.startActivity(intent);
    }

    /**
     * 启动编辑冰柜页面
     */
    public static void startForEdit(Context context, FreezerDetailBean freezerData) {
        Intent intent = new Intent(context, FreezerEditActivity.class);
        intent.putExtra(IntentKey.TYPE, TYPE_EDIT);
        intent.putExtra(IntentKey.DATA, freezerData);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.freezer_edit_activity;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        // 标题栏
        mTitleBar = findViewById(R.id.tb_title);

        // 冰柜管理
        mFreezerNameLabel = findViewById(R.id.tv_freezer_name_label);
        mFreezerNameEdit = findViewById(R.id.et_freezer_name);
        mNameplateCodeLabel = findViewById(R.id.tv_nameplate_code_label);
        mNameplateCodeEdit = findViewById(R.id.et_nameplate_code);
        mFreezerTypeLabel = findViewById(R.id.tv_freezer_type_label);
        mFreezerTypeValue = findViewById(R.id.tv_freezer_type_value);
        mTerminalNameLabel = findViewById(R.id.tv_terminal_name_label);
        mTerminalNameValue = findViewById(R.id.tv_terminal_name_value);
        mTerminalCodeValue = findViewById(R.id.tv_terminal_code_value);
        mHasSubsidyLabel = findViewById(R.id.tv_has_subsidy_label);
        mSubsidyYesCheckBox = findViewById(R.id.cb_subsidy_yes);
        mSubsidyNoCheckBox = findViewById(R.id.cb_subsidy_no);
        mIsPlacedLabel = findViewById(R.id.tv_is_placed_label);
        mPlacedYesCheckBox = findViewById(R.id.cb_placed_yes);
        mPlacedNoCheckBox = findViewById(R.id.cb_placed_no);
        mSubsidyAmountLabel = findViewById(R.id.tv_subsidy_amount_label);
        mSubsidyAmountEdit = findViewById(R.id.et_subsidy_amount);
        mFreezerPhotoLabel = findViewById(R.id.tv_freezer_photo_label);
        mFreezerPhotoView = findViewById(R.id.iv_freezer_photo);
        mFreezerPhotoDeleteView = findViewById(R.id.iv_freezer_photo_delete);
        mNameplatePhotoLabel = findViewById(R.id.tv_nameplate_photo_label);
        mNameplatePhotoView = findViewById(R.id.iv_nameplate_photo);
        mNameplatePhotoDeleteView = findViewById(R.id.iv_nameplate_photo_delete);

        // 配送商信息
        mDeliveryProviderLabel = findViewById(R.id.tv_delivery_provider_label);
        mDeliveryProviderValue = findViewById(R.id.tv_delivery_provider_value);
        mVehicleCodeLabel = findViewById(R.id.tv_vehicle_code_label);
        mVehicleCodeValue = findViewById(R.id.tv_vehicle_code_value);
        mSalespersonLabel = findViewById(R.id.tv_salesperson_label);
        mSalespersonValue = findViewById(R.id.tv_salesperson_value);
        mSalesAreaLabel = findViewById(R.id.tv_sales_area_label);
        mSalesAreaValue = findViewById(R.id.tv_sales_area_value);

        // 保存按钮（使用内部按钮 ID）
        mSaveButton = findViewById(R.id.tv_bottom_button);

        // 设置必填标记
        TextStarUtils.setRequiredText(mFreezerNameLabel, getString(R.string.freezer_name));
        TextStarUtils.setRequiredText(mNameplateCodeLabel, getString(R.string.nameplate_code));
        TextStarUtils.setRequiredText(mFreezerTypeLabel, "冰柜类型");
        TextStarUtils.setRequiredText(mHasSubsidyLabel, getString(R.string.has_subsidy));
        TextStarUtils.setRequiredText(mIsPlacedLabel, getString(R.string.is_placed));
        TextStarUtils.setRequiredText(mSubsidyAmountLabel, getString(R.string.subsidy_amount));
        TextStarUtils.setRequiredText(mFreezerPhotoLabel, getString(R.string.freezer_photo));
        TextStarUtils.setRequiredText(mDeliveryProviderLabel, "配送商");
        TextStarUtils.setRequiredText(mVehicleCodeLabel, "车辆编码");
        TextStarUtils.setRequiredText(mSalespersonLabel, "业务员");
        TextStarUtils.setRequiredText(mSalesAreaLabel, getString(R.string.sales_area));

        // 设置金额输入限制
        MoneyInputHelper.setMoneyInput(mSubsidyAmountEdit);

        // 设置单选CheckBox的互斥逻辑
        setupCheckBoxGroup(mSubsidyYesCheckBox, mSubsidyNoCheckBox);
        setupCheckBoxGroup(mPlacedYesCheckBox, mPlacedNoCheckBox);

        // 设置图片点击事件
        mFreezerPhotoView.setOnClickListener(v -> {
            mCurrentPhotoType = PHOTO_TYPE_FREEZER;
            ImageSelectActivity.start(this, 1, this);
        });
        mNameplatePhotoView.setOnClickListener(v -> {
            mCurrentPhotoType = PHOTO_TYPE_NAMEPLATE;
            ImageSelectActivity.start(this, 1, this);
        });

        // 设置图片删除按钮点击事件
        mFreezerPhotoDeleteView.setOnClickListener(v -> deleteFreezerPhoto());
        mNameplatePhotoDeleteView.setOnClickListener(v -> deleteNameplatePhoto());

        // 设置点击事件
        setOnClickListener(mFreezerTypeValue, mTerminalNameValue, mDeliveryProviderValue, mSaveButton);
    }

    @Override
    protected void initData() {
        // 获取编辑类型
        mEditType = getInt(IntentKey.TYPE, TYPE_ADD);

        // 设置标题
        if (mEditType == TYPE_EDIT) {
            mTitleBar.setTitle(getString(R.string.edit_freezer));
            // 获取数据并填充
            mFreezerData = (FreezerDetailBean) getSerializable(IntentKey.DATA);
            if (mFreezerData != null) {
                fillData();
            }
        } else {
            mTitleBar.setTitle(getString(R.string.add_freezer));
        }
    }

    /**
     * 填充数据（编辑模式）
     */
    private void fillData() {
        if (mFreezerData == null) return;

        mFreezerNameEdit.setText(mFreezerData.getFreezerName());
        mNameplateCodeEdit.setText(mFreezerData.getFreezerNameplateCode());
        mFreezerTypeValue.setText(mFreezerData.getFreezerType());
        mTerminalNameValue.setText(mFreezerData.getTerminalName());
        mTerminalCodeValue.setText(mFreezerData.getTerminalCode());
        
        // 单选框
        if (mFreezerData.isSubsidized()) {
            mSubsidyYesCheckBox.setChecked(true);
        } else {
            mSubsidyNoCheckBox.setChecked(true);
        }
        
        if (mFreezerData.isPlaced()) {
            mPlacedYesCheckBox.setChecked(true);
        } else {
            mPlacedNoCheckBox.setChecked(true);
        }
        
        mSubsidyAmountEdit.setText(mFreezerData.getSubsidyAmount());
        
        // 配送商信息
        mDeliveryProviderValue.setText(mFreezerData.getDeliveryProvider());
        mVehicleCodeValue.setText(mFreezerData.getVehicleCode());
        mSalespersonValue.setText(mFreezerData.getSalesperson());
        mSalesAreaValue.setText(mFreezerData.getSalesArea());
        
        // 照片
        mFreezerPhotoPath = mFreezerData.getFreezerPhotoPath();
        mNameplatePhotoPath = mFreezerData.getNameplatePhotoPath();
        updateFreezerPhoto();
        updateNameplatePhoto();
    }

    /**
     * 设置CheckBox互斥逻辑（单选）
     * 
     * @param checkBox1 第一个CheckBox
     * @param checkBox2 第二个CheckBox
     */
    private void setupCheckBoxGroup(CheckBox checkBox1, CheckBox checkBox2) {
        checkBox1.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked && checkBox2.isChecked()) {
                checkBox2.setChecked(false);
            }
        });

        checkBox2.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked && checkBox1.isChecked()) {
                checkBox1.setChecked(false);
            }
        });
    }

    @SingleClick
    @Override
    public void onClick(View view) {
        super.onClick(view);
        int id = view.getId();
        if (id == R.id.tv_freezer_type_value) {// 选择冰柜类型
            List<String> options = new ArrayList<>();
            options.add("类型1");
            options.add("类型2");
            options.add("类型3");
            options.add("类型4");
            options.add("类型5");
            new SelectionListDialog.Builder(this)
                    .setTitle("冰柜类型")
                    .setDataList(options)
                    .setListener(new SelectionListDialog.OnListener() {
                        @Override
                        public void onSelected(BaseDialog dialog, String selectedItem, int position) {
                            mFreezerTypeValue.setText(selectedItem);
                        }
                    })
                    .show();
        } else if (id == R.id.tv_terminal_name_value) {// 选择终端
            new SelectSubmitterDialog.Builder(this,102)//102 = 只显示终端
                    .setListener(new SelectSubmitterDialog.OnListener() {
                        @Override
                        public void onSelected(BaseDialog dialog, String submitter, int type, Object data) {
                            mTerminalNameValue.setText(submitter);
                        }
                    })
                    .show();
        } else if (id == R.id.tv_delivery_provider_value) {// 选择配送商
            new SelectSubmitterDialog.Builder(this,101)//101 = 只显示配送商
                    .setListener(new SelectSubmitterDialog.OnListener() {
                        @Override
                        public void onSelected(BaseDialog dialog, String submitter, int type, Object data) {
                            mDeliveryProviderValue.setText(submitter);
                        }
                    })
                    .show();
        } else if (id == R.id.tv_bottom_button) {
            // 保存
            submitData();
        }
    }

    /**
     * {@link ImageSelectActivity.OnPhotoSelectListener}
     * 图片选择回调
     */
    @Override
    public void onSelected(List<String> images) {
        if (images != null && !images.isEmpty()) {
            String imagePath = images.get(0);
            if (mCurrentPhotoType == PHOTO_TYPE_FREEZER) {
                mFreezerPhotoPath = imagePath;
                updateFreezerPhoto();
            } else if (mCurrentPhotoType == PHOTO_TYPE_NAMEPLATE) {
                mNameplatePhotoPath = imagePath;
                updateNameplatePhoto();
            }
        }
    }

    @Override
    public void onCancel() {
        // 取消选择
    }

    /**
     * 更新冰柜照片显示
     */
    private void updateFreezerPhoto() {
        if (!TextUtils.isEmpty(mFreezerPhotoPath) && new File(mFreezerPhotoPath).exists()) {
            GlideApp.with(this)
                    .load(new File(mFreezerPhotoPath))
                    .placeholder(R.drawable.add_ic)
                    .error(R.drawable.add_ic)
                    .into(mFreezerPhotoView);
            mFreezerPhotoView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            mFreezerPhotoDeleteView.setVisibility(View.VISIBLE);
        } else {
            mFreezerPhotoView.setImageResource(R.drawable.add_ic);
            mFreezerPhotoView.setScaleType(ImageView.ScaleType.CENTER);
            mFreezerPhotoDeleteView.setVisibility(View.GONE);
        }
    }

    /**
     * 更新铭牌照片显示
     */
    private void updateNameplatePhoto() {
        if (!TextUtils.isEmpty(mNameplatePhotoPath) && new File(mNameplatePhotoPath).exists()) {
            GlideApp.with(this)
                    .load(new File(mNameplatePhotoPath))
                    .placeholder(R.drawable.add_ic)
                    .error(R.drawable.add_ic)
                    .into(mNameplatePhotoView);
            mNameplatePhotoView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            mNameplatePhotoDeleteView.setVisibility(View.VISIBLE);
        } else {
            mNameplatePhotoView.setImageResource(R.drawable.add_ic);
            mNameplatePhotoView.setScaleType(ImageView.ScaleType.CENTER);
            mNameplatePhotoDeleteView.setVisibility(View.GONE);
        }
    }

    /**
     * 删除冰柜照片
     */
    @SingleClick
    private void deleteFreezerPhoto() {
        mFreezerPhotoPath = null;
        updateFreezerPhoto();
        toast("已删除冰柜照片");
    }

    /**
     * 删除铭牌照片
     */
    @SingleClick
    private void deleteNameplatePhoto() {
        mNameplatePhotoPath = null;
        updateNameplatePhoto();
        toast("已删除铭牌照片");
    }

    /**
     * 提交数据
     */
    private void submitData() {
        // TODO: 验证必填项

        // 获取表单数据
        String freezerName = mFreezerNameEdit.getText().toString().trim();
        String nameplateCode = mNameplateCodeEdit.getText().toString().trim();
        String freezerType = mFreezerTypeValue.getText().toString().trim();
        String terminalName = mTerminalNameValue.getText().toString().trim();
        String terminalCode = mTerminalCodeValue.getText().toString().trim();
        boolean isSubsidized = mSubsidyYesCheckBox.isChecked();
        boolean isPlaced = mPlacedYesCheckBox.isChecked();
        String subsidyAmount = mSubsidyAmountEdit.getText().toString().trim();
        String deliveryProvider = mDeliveryProviderValue.getText().toString().trim();
        String vehicleCode = mVehicleCodeValue.getText().toString().trim();
        String salesperson = mSalespersonValue.getText().toString().trim();
        String salesArea = mSalesAreaValue.getText().toString().trim();

        // TODO: 提交到服务器

        if (mEditType == TYPE_EDIT) {
            toast("编辑成功");
        } else {
            toast("新增成功");
        }
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 释放资源
    }
}
